package com.coinbixin.ui.quick_purchase;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListPopupWindow;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.coinbixin.app.MyApplication;
import com.coinbixin.ui.setting.GongGaoActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gyf.barlibrary.ImmersionBar;
import com.coinbixin.R;
import com.coinbixin.ui.message_detail.MessageDetailActivity;
import com.coinbixin.adapter.GongGaoAdapter;
import com.coinbixin.base.BaseActivity;
import com.coinbixin.base.LinListView;
import com.coinbixin.app.UrlFactory;
import com.coinbixin.utils.WonderfulLogUtils;
import com.coinbixin.utils.okhttp.StringCallback;
import com.coinbixin.utils.okhttp.WonderfulOkhttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Request;

import static com.coinbixin.utils.WonderfulDpPxUtils.dip2px;

/**
 * Created by Administrator on 2018/8/9.
 */
public class BuyBillDetailActivity extends BaseActivity {
    @BindView(R.id.tv_bill_num2)
    TextView tv_bill_num2;
    @BindView(R.id.tv_bill_prices)
    TextView tv_bill_prices;
    @BindView(R.id.tv_bank_username)
    TextView tv_bank_username;
    @BindView(R.id.tv_bank_name)
    TextView tv_bank_name;
    @BindView(R.id.tv_bank_down)
    TextView tv_bank_down;
    @BindView(R.id.tv_bank_number)
    TextView tv_bank_number;
    @BindView(R.id.quickbuy_ibBack)
    ImageButton quickbuy_ibBack;
    @BindView(R.id.tv_cancel_bill)
    TextView tv_cancel_bill;
    @BindView(R.id.tv_sure_pay)
    TextView tv_sure_pay;
    @BindView(R.id.tv_exit)
    TextView tv_exit;
    @BindView(R.id.tv_bill_total2)
    TextView tv_bill_total2;
    @BindView(R.id.tv_bill_second)
    TextView tv_bill_second;
    @BindView(R.id.tv_bill_minter)
    TextView tv_bill_minter;

    private static byte detail_pay_id;
    private static int detail_num;
    private static float detail_total;
    private static float detail_price;
    private static int bill_id=0;

    private UIHandler mHandler = new UIHandler();
    private Thread mThread;
    private boolean flag = true;

    @Override
    protected int getActivityLayoutId() {
        return R.layout.activity_buy_detail_info;
    }
    public static void actionStart(Activity context, float price, byte pay_id, int num, float total) {
        detail_price = price;
        detail_pay_id = pay_id;
        detail_num = num;
        detail_total = total;
        Intent intent = new Intent(context, BuyBillDetailActivity.class);
        context.startActivityForResult(intent,1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable  Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

    private class UIHandler extends Handler {
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            if(msg.what==1) {
                int second = Integer.parseInt(tv_bill_second.getText().toString());
                int minter = Integer.parseInt(tv_bill_minter.getText().toString());
                int time = minter*60+second;
                if(time!=0)
                {
                    time--;
                    second = time % 60;
                    minter = time / 60;
                    tv_bill_minter.setText(String.valueOf(minter));
                    tv_bill_second.setText(String.valueOf(second));
                    }
                }else {
                tv_sure_pay.setEnabled(false);
                }
            }
        }

    @Override
    protected void initViews(Bundle savedInstanceState) {

        tv_bill_num2.setText(String.valueOf(detail_num)+" USDT");
        tv_bill_prices.setText(String.valueOf(detail_total)+" TWD");
        tv_bill_total2.setText(String.valueOf(detail_total)+" TWD");

        quickbuy_ibBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent();
                setResult(2,i);
                flag = false;
                finish();
            }
        });

        mThread = new Thread(new Runnable()
        {
            @Override
            public void run() {
                   int i=0;
                   while(flag&&i++<29*60+59)
                    {
                        Message msg = new Message();
                        msg.what=1;
                        mHandler.sendMessage(msg);
                        try {
                            Thread.sleep(1000);
                        }catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
            }
        });

        mThread.start();

        tv_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent();
                setResult(2,i);
                flag = false;
                finish();
            }
        });

        tv_cancel_bill.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flag=false;
                displayLoadingPopup();
                CancelBill();
            }
        });

        tv_sure_pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flag=false;
                displayLoadingPopup();
                SureBill();
            }
        });

    }

    private void CancelBill() {
        WonderfulOkhttpUtils.post().url(UrlFactory.cancelCrcOrder()).addHeader("x-auth-token", getToken())
                .addParams("oid",String.valueOf(bill_id))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                hideLoadingPopup();
            }

            @Override
            public void onResponse(String response) {
                WonderfulLogUtils.logi("miao",response);
                hideLoadingPopup();
                try {
                    JSONObject object = new JSONObject(response);
                    if (object.optInt("data") == 0)
                    {
                       //JSONObject ob1 = object.getJSONObject("data");
                       int code = object.getInt("code");
                       //int id = ob1.getInt("id");
                       String msg = object.getString("message");

                       Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void SureBill() {
        WonderfulOkhttpUtils.post().url(UrlFactory.SureCrdOrder()).addHeader("x-auth-token", getToken())
                .addParams("oid",String.valueOf(bill_id))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                hideLoadingPopup();
            }

            @Override
            public void onResponse(String response) {
                WonderfulLogUtils.logi("miao",response);
                hideLoadingPopup();
                try {
                    JSONObject object = new JSONObject(response);
                    if (object.optInt("data") == 0)
                    {
                        int code = object.getInt("code");
                        //int id = ob1.getInt("id");
                        String msg = object.getString("message");

                        Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void obtainData() {

    }

    @Override
    protected void fillWidget() {

    }


    @Override
    protected void loadData() {
        displayLoadingPopup();
        getMessage();
    }

    private void getMessage() {
        WonderfulOkhttpUtils.post().url(UrlFactory.getNewOrder()).addHeader("x-auth-token", getToken())
                .addParams("price",String.valueOf(detail_price))
                .addParams("amount",String.valueOf(detail_num)).addParams("payType","bank")
                .addParams("direction","0").addParams("unit","USDT").addParams("fundpwd","").addParams("code","")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                hideLoadingPopup();
            }

            @Override
            public void onResponse(String response) {
                WonderfulLogUtils.logi("miao",response);
                hideLoadingPopup();
                try {
                    JSONObject object = new JSONObject(response);
                    if (object.optInt("data") == 0)
                    {

                        int codeId = object.getInt("code");
                        String msg = object.getString("message");
                        if(codeId==0)
                        {
                            JSONObject ob1 = object.getJSONObject("data");
                            bill_id = ob1.getInt("id");
                            String realName = ob1.getString("realName");
                            JSONObject ob2 = ob1.getJSONObject("bankInfo");
                            String bank = ob2.getString("bank");
                            String branch = ob2.getString("branch");
                            String cardNo = ob2.getString("cardNo");

                            tv_bank_username.setText(realName);
                            tv_bank_name.setText(bank);
                            tv_bank_down.setText(branch);
                            tv_bank_number.setText(cardNo);
                        }else{

                        }

                        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            flag = false;
            Intent i = new Intent();
            setResult(2,i);
            finish();
            return true;
        }else{
            return super.onKeyDown(keyCode, event);
        }

    }
}
